package com.office.app.system.action;

import com.jfinal.aop.Before;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.office.app.system.action.validate.UserValidator;
import com.office.app.system.model.Role;
import com.office.app.system.model.User;
import com.office.framework.common.BaseController;
import com.office.framework.common.Result;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;

import java.util.List;

/**
 * Created by jyyco on 2015/7/17.
 */
public class UserController extends BaseController {

    public void index() {
        User user = getModel(User.class);
        Page<User> page = User.dao.paginate(getParaToInt("pageNo", 1), 10, user);
        setAttr("page", page);
        keepModel(User.class);
        render("user/list.html");
    }

    public void add() {
        user=new User();
        setAttr("roles", Role.dao.getAll());
        setAttr("user",user);
        render("user/add.html");
    }



    public void edit() {
        setAttr("user", User.dao.get(getParaToInt()));
        List<Role> roles = Role.dao.getAll();
        List<Role> rs = User.dao.getRoles(getParaToInt());
        for(Role role : roles) {
            for(Role r : rs) {
                if(role.getInt("id").intValue() == r.getInt("id").intValue())
                {
                    role.put("selected", 1);
                }
                if(role.get("selected") == null)
                {
                    role.put("selected", 0);
                }
            }
        }
        setAttr("roles", roles);
        render("user/edit.html");

    }

    public void view() {

        setAttr("user", User.dao.get(getParaToInt()));
        List<Role> roles = Role.dao.getAll();
        List<Role> rs = User.dao.getRoles(getParaToInt());
        for(Role role : roles) {
            for(Role r : rs) {
                if(role.getInt("id").intValue() == r.getInt("id").intValue())
                {
                    role.put("selected", 1);
                }
                if(role.get("selected") == null)
                {
                    role.put("selected", 0);
                }
            }
        }
        setAttr("roles", roles);
        render("user/view.html");
    }

    @Before({UserValidator.class, Tx.class})
    public void save() {
        Integer[] orderIndexs = getParaValuesToInt("orderIndexs");
        User model = getModel(User.class);
        if (StringUtils.isNotBlank(model.getStr("plainPassword"))) {
            model.entryptPassword(model);
        }
        model.save();
        if(orderIndexs != null) {
            for(Integer orderIndex : orderIndexs) {
                User.dao.insertCascade(model.getInt("id"), orderIndex);
            }
        }
        Result result=new Result();
        result.setMessage("");

        renderJson(result);
        //redirect("/security/user");
    }

    @Before({UserValidator.class, Tx.class})
    public void update() {
        Integer[] orderIndexs = getParaValuesToInt("orderIndexs");
        User model = getModel(User.class);
        if (StringUtils.isNotBlank(model.getStr("plainPassword"))) {
            model.entryptPassword(model);
        }
        model.update();
        User.dao.deleteCascade(model.getInt("id"));
        if(orderIndexs != null) {
            for(Integer orderIndex : orderIndexs) {
                User.dao.insertCascade(model.getInt("id"), orderIndex);
            }
        }
        redirect("/security/user");
    }

    @Before(Tx.class)
    public void delete() {
        User.dao.deleteCascade(getParaToInt());
        User.dao.deleteById(getParaToInt());
        redirect("/security/user");
    }

    @ActionKey("/login")
    public void login() {
        keepModel(User.class);
        render("login.html");
    }



    private User user;
    public void dologin() {
        String error = "";
        String username = getPara("user.username");
        String password = getPara("user.password");
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            error ="帐号密码不能为空";
        }
        if(StringUtils.isEmpty(error)) {
            //Subject subject = SecurityUtils.getSubject();
            //UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
               // subject.login(token);
                error=getLogin(username,password);
            } catch(UnknownAccountException ue) {
                //token.clear();
                error = "登录失败，您输入的账号不存在";
            } catch(IncorrectCredentialsException ie) {
                ie.printStackTrace();
               // token.clear();
                error = "登录失败，密码不匹配";
            } catch(RuntimeException re) {
                re.printStackTrace();
                //token.clear();
                error = "登录失败";
            }
        }
        if(StringUtils.isEmpty(error)) {
            redirect("/system/");
        } else {
            keepModel(User.class);
            setAttr("error", error);
            render("login.html");
        }
    }

    private String getLogin(String username,String password)
    {
        User model=User.dao.getByName(username);
        if(model==null) {
            return "登录失败，您输入的账号不存在";
        }else{
            if(model.get("password").equals(password))
            {
                return "";
            }else{
                return "登录失败，密码不匹配";
            }
        }
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}
